from multiprocessing import Process,Queue,Value
import os,time

# 队列实现进程之间数据共享
# a = 100
# def write_queue(arg):
#     print('写入开始')
#     global a
#     if not arg.full():
#         for i in range(10) :
#             a-=5
#             print('入队时a的值为',a)
#             arg.put(a)
#
#     print('入队结束')
#
# def read_queue(arg):
#     print('读取开始')
#     time.sleep(1)
#     if not arg.empty():
#         for i in range(10):
#             rs = arg.get()
#             print('出队时a的值为', rs)
#
#     print('读取结束')
#
#
# if __name__ == '__main__':
#     print('parents start....')
#     q = Queue() # 不写参数，表示接收无上限
#     p1 = Process(target=write_queue, args=(q,))
#     p2 = Process(target=read_queue, args=(q,))
#     p1.start()
#     p2.start()
#     p1.join()
#     p2.join()
#     print('parents end....')


def sub_process1(arg):
    print(f'子进程{arg}开始执行')
    with arg.get_lock():
        arg.value+=10
    print(f'子进程{arg}结束执行')

def sub_process2(arg):
    print(f'子进程{arg}开始执行')
    with arg.get_lock():
        arg.value -= 50
    print(f'子进程{arg}结束执行')


if __name__ == '__main__':
    a = Value('i',100)
    start = time.time()
    print('parents start')
    p1 = Process(target=sub_process1, args=(a,))
    p2 = Process(target=sub_process2, args=(a,))

    p1.start()
    p2.start()
    p1.join()
    p2.join()

    print('parents end')
    print(a.value)
    print(time.time() - start)
